#coding:utf8
'''
Created on 2011-5-24

@author: mark
'''

import Image
import ImageDraw
import ImageFont
import StringIO
import string
import web

import config

def generateCapture(captcha, word):
    # Create a background image
    image = Image.new('RGB', (300, 50), (220, 210, 190))
    draw = ImageDraw.Draw(image)
 
    # Create a text image
    textImg = Image.new('RGB', (150, 40), (0, 0, 0))
    tmpDraw = ImageDraw.Draw(textImg)
    textFont = ImageFont.truetype(config.fontpath, 36)
    tmpDraw.text((0, 0), word, font=textFont, fill=(10, 200, 200))
    textImg = textImg.rotate(-10)
 
    # Create a mask (same size as the text image)
    mask = Image.new('L', (150, 40), 0)
    mask.paste(textImg, (0, 0))
 
    # Paste text image with the mask
    image.paste(textImg, (100, 0), mask)
 
    image.save(captcha, "JPEG")
    
letters = string.digits + string.letters

class Captcha:
    def GET(self):
        def getWords():
            import random
            return "".join([random.choice(letters) for i in range(6)])
        words = getWords()
        
        web.ctx.session['captcha'] = words
        captcha = StringIO.StringIO()
        generateCapture(captcha, words)
        
        web.header("Content-Type", "image/JPEG")
        
        return captcha.getvalue()
        
        
